package com.jb.repair.acticity;

import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RemoteViews;
import android.widget.TextView;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jb.repair.F1Application;
import com.jb.repair.R;
import com.jb.repair.common.AppConfig;
import com.jb.repair.common.Constants;
import com.jb.repair.common.DialogCallBack;
import com.jb.repair.dao.Db;
import com.jb.repair.dao.ModifyDb;
import com.jb.repair.dao.QueryDb;
import com.jb.repair.model.FileLbModel;
import com.jb.repair.model.TaskModel;
import com.jb.repair.model.User4Json;
import com.jb.repair.net.HttpClient;
import com.jb.repair.net.HttpCookies;
import com.jb.repair.util.FileUtil;
import com.jb.repair.util.MemoryUtil;
import com.jb.repair.util.MessageUtil;
import com.jb.repair.util.NetUtil;
import com.jb.repair.view.TitleView;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ConfigActivity extends BaseActivity implements DialogCallBack {

    private TitleView titleView;
    private EditText edtServiceAddress;//服务地址
    private TextView tvTest;
    private TextView tvUpdateTime;
    private RequestQueue mQueue;
    private ProgressDialog pdialog;
    SharedPreferences sp;
    private HomeWatchereciver reciver = null;

    String dbPath = AppConfig.DB_PATh;
    String url;
    private long fileSize = 100L;     //所要下载的文件大小
    private long dbSize = 100L;
    private long size = 100L;
    private long currentFileSize = 0;
    private static final int WIFI_DIALOG = 1;
    private static final int MEMORY_DIALOG = 2;
    private static final int LOGIN_VALIDATA_DIALOG = 3;
    private static final int NO_NET_DIALOG = 4;
    private static final String TAG = "ConfigActivity";
    private int file_num = 1;   //所要下载的文件个数
    // private Boolean isDownFile;    //是否下载附件
    private List<FileLbModel> fileList = new ArrayList<>();

    private NotificationManager manager;
    private Notification notif;
    private Boolean isDowning = false;
    private Boolean isShowNotify = false;
    private int persent = 0;

    @Override
    protected void onResume() {
        super.onResume();
        registerHomeKeyReceiver(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterHomeKeyReceiver(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_config);

        Log.i("gaobin", MemoryUtil.getAvailableExternalMemorySize() + "");
        Log.i("gaobin", AppConfig.BASE_PATH);

        mQueue = Volley.newRequestQueue(this);
        sp = getSharedPreferences(Constants.SP_NAME, MODE_PRIVATE);
        titleView = (TitleView) findViewById(R.id.titleView);
        edtServiceAddress = (EditText) findViewById(R.id.edtServiceAddress);
        edtServiceAddress.setText(sp.getString(Constants.SERVICE_ADDRESS, "http://zhrx.joinbright.com:8113/relay/"));
        tvTest = (TextView) findViewById(R.id.tv_test);

        titleView.setOnClickListener(new TitleView.OnTitleViewClickListener() {
            @Override
            public void onRightTextClick(View view) {
                Log.i(TAG, "点击了确认按钮");
                super.onRightTextClick(view);
                //将服务地址保存到sharedpreference中
                String url = edtServiceAddress.getText().toString();
                if (!url.endsWith("/"))
                    url = url + "/";
                sp.edit().putString(Constants.SERVICE_ADDRESS, url).commit();
//                AppConfig.BASE_URL = url;
                Log.i(TAG, "保存的服务地址为：" + sp.getString(Constants.SERVICE_ADDRESS, "空"));
                MessageUtil.showToast(getApplicationContext(), "保存成功");
            }

            @Override
            public void onLeftImageClick(View view) {
                super.onLeftImageClick(view);
                Log.i(TAG, "点击了返回箭头");
                ConfigActivity.this.finish();
            }
        });

        tvTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String url = edtServiceAddress.getText().toString();
                if (!url.endsWith("/"))
                    url = url + "/";
                sp.edit().putString(Constants.SERVICE_ADDRESS, url).commit();
                Log.i(TAG, "点击了测试按钮");
                //先查看是否有网
                if (NetUtil.isNetOK(ConfigActivity.this))
                    test();
                else
                    MessageUtil.showPopDialog(getApplicationContext(), tvTest, "网络连接失败", "无法连接网络，请检测网络设置", "去设置", NO_NET_DIALOG, ConfigActivity.this);
            }
        });
        tvUpdateTime = (TextView) findViewById(R.id.tv_update_time);
        tvUpdateTime.setText(sp.getString(Constants.DB_UPDATE_TIME, ""));

        findViewById(R.id.tv_down_db).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG, "点击了下载数据库");
                downAllFile();
            }
        });
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        File file = new File(AppConfig.DB_PATh);
        if (file.exists()) {
            Log.i(TAG, "已下载数据库跳转到登陆页");
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            finish();
        } else {
            Log.i(TAG, "未下载数据库退出程序");
            F1Application.exit();
        }
    }

    private void showFirstDownPop() {
        View popView = LayoutInflater.from(this).inflate(R.layout.pop_first_down, null);
        final PopupWindow pop = new PopupWindow(popView, (int) getResources().getDimension(R.dimen.x400), ViewGroup.LayoutParams.WRAP_CONTENT, true);
        pop.setFocusable(true);
        ColorDrawable dw = new ColorDrawable(0x00000000);
        pop.setBackgroundDrawable(dw);
        pop.showAtLocation(tvTest, Gravity.CENTER, 0, 0);
        popView.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop.dismiss();
            }
        });
        /*  final ToggleButton tb = (ToggleButton) popView.findViewById(R.id.rb);*/
        popView.findViewById(R.id.btn_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                size = dbSize;


                if (size >= MemoryUtil.getAvailableExternalMemorySize()) {
                    MessageUtil.showDialog(ConfigActivity.this, "内存不足", "内存不足请清除缓存后再试!", MEMORY_DIALOG, ConfigActivity.this);
                } else {
                    new DownLoadFile().execute();
                }
                pop.dismiss();
            }
        });
    }

    private void downAllFile() {
        if (!NetUtil.isNetOK(this)) {
            MessageUtil.showPopDialog(getApplicationContext(), tvTest, "网络连接失败失败", "无法连接网络，请检测网络设置", "去设置", NO_NET_DIALOG, ConfigActivity.this);
            return;
        }
        if (!NetUtil.isWifi(this)) {
            MessageUtil.showDialog(this, "提示", "非WIFI网络是否继续下载", WIFI_DIALOG, this);
        } else {
            if (HttpCookies.getSessionId() == null || HttpCookies.getSessionId().equals("")) {
                Log.i(TAG, "未登陆，在线验证");
                MessageUtil.showLoginValidataPop(getApplicationContext(), tvTest, LOGIN_VALIDATA_DIALOG, ConfigActivity.this);
            } else {
                Log.i(TAG, "已登陆");
                new GetFileSizeTask().execute(Constants.GET_FILE_SIZE_URL);
            }
        }
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        pdialog = new ProgressDialog(this);
        pdialog.setMax(100);
        pdialog.setMessage("正在下载...");
        pdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pdialog.setIndeterminate(false);
        pdialog.setCancelable(false);
        pdialog.show();
        return pdialog;
    }

    /**
     * 测试服务地址
     */
    private void test() {
        MessageUtil.showProgressDialog(this, "正在测试");
        url = edtServiceAddress.getText().toString();
        if (!url.endsWith("/")) {
            url = url + "/";
        }
        Log.i(TAG, "url = " + url);
        final String finalUrl = url;

        StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                MessageUtil.dismissProgressDialog();
                Log.i(TAG, "response=" + s);
                MessageUtil.showToast(getApplicationContext(), "测试成功");
                AppConfig.BASE_URL = finalUrl;
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                MessageUtil.dismissProgressDialog();
                MessageUtil.showToast(getApplicationContext(), "测试失败");
            }

        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(3000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        mQueue.add(stringRequest);
    }

    @Override
    public void onResult(int requsetViewId, Bundle bundle) {
        switch (requsetViewId) {
            case WIFI_DIALOG:  //非wifi网络Dialog监听
                if (bundle.getInt("data") == Constants.UPDATE_YES) {
                    if (HttpCookies.getSessionId() == null || HttpCookies.getSessionId().equals("")) {
                        Log.i(TAG, "未登陆，在线验证");
                        MessageUtil.showLoginValidataPop(getApplicationContext(), tvTest, LOGIN_VALIDATA_DIALOG, ConfigActivity.this);
                    } else {
                        Log.i(TAG, "已登陆");
                        new GetFileSizeTask().execute(Constants.GET_FILE_SIZE_URL);
                    }
                }
                break;
            case MEMORY_DIALOG:   //存储空间不足弹窗监听
                if (bundle.getInt("data") == Constants.UPDATE_YES) {
                }
                break;
            case LOGIN_VALIDATA_DIALOG:   //在线验证弹窗监听
                // Log.i(TAG,"在线验证确定");
                if (!NetUtil.isNetOK(getApplicationContext())) {
                    MessageUtil.showPopDialog(getApplicationContext(), tvTest, "网络连接失败", "无法连接网络，请检测网络设置", "去设置", NO_NET_DIALOG, ConfigActivity.this);
                }
                String userName = bundle.getString("userName");
                new LoginTask().execute(userName, bundle.getString("pwd"));
                Log.i(TAG, "username：" + userName);
                break;
            case NO_NET_DIALOG:   //无网络的弹窗监听
                Intent wifiSettingsIntent = new Intent("android.settings.WIFI_SETTINGS");
                startActivity(wifiSettingsIntent);
                break;
        }
    }

    /**
     * 下载文件，第一个参数为下载地址，第二个参数为文件的绝对路径
     */
    class DownLoadFile extends AsyncTask<String, Integer, Boolean> {
        /* 后台线程 */
        @Override
        protected Boolean doInBackground(String... params) {
            try {
                String url = AppConfig.BASE_URL + Constants.DOWN_DB_URL;
                Log.i(TAG, "下载数据库地址" + url);
                isDowning = true;
                persent = 0;
                DefaultHttpClient client = new DefaultHttpClient();
                HttpGet httpRequest = new HttpGet(url);
                httpRequest.setHeader("Accept-Encoding", "gzip");// 设置压缩格式
                HttpCookies li = new HttpCookies(getApplicationContext());
                CookieStore cs = li.getuCookie();
                if (cs != null) {
                    client.setCookieStore(li.getuCookie());
                }
                HttpResponse httpResponse = client.execute(httpRequest);
                int resCode = httpResponse.getStatusLine().getStatusCode();
                Log.i(TAG, "下载数据库返回code：" + resCode);

                if (resCode == 601) {
                    MessageUtil.showToast(getApplicationContext(), "网络异常，请重试");
                    dismissDialog(0);
                }

                if (resCode == 200) {
                    HttpEntity entity = httpResponse.getEntity();
                    int length = 0;
                    InputStream in = entity.getContent();
                    String path = AppConfig.DB_FILE_PATh;
                    File file = new File(path);
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    FileOutputStream out = new FileOutputStream(new File(AppConfig.DB_PATh + ".zip"));
                    byte[] buff = new byte[1024 * 1024 * 4];
                    // Log.i(TAG, "总下载量" + size);
                    while ((length = in.read(buff)) > 0) {
                        currentFileSize += (length);
                        int str1 = (int) (currentFileSize * 100 / size);
                        //       Log.i(TAG, "已下载:" + currentFileSize);
                        if (str1 - persent == 1) {
                            persent = str1;
                            publishProgress(str1);
                            if (isShowNotify) {
                                if (str1 % 3 == 0) {
                                    notif.contentView.setTextViewText(R.id.content_view_text1, str1 + "%");
                                    notif.contentView.setProgressBar(R.id.content_view_progress, 100, str1, false);
                                    manager.notify(0, notif);
                                }
                            }
                        }
                        out.write(buff, 0, length);
                    }
                    in.close();
                    out.flush();
                    out.close();
                }
            } catch (Exception e) {
                isDowning = false;
                return false;
            }
            return true;
        }


        /* 预处理UI线程 */
        @Override
        protected void onPreExecute() {
            showDialog(0);
            currentFileSize = 0;
            pdialog.setProgress(0);
            super.onPreExecute();
        }

        /* 结束时的UI线程 */
        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            if (result) {
                try {
                    F1Application.setDBUpdateDate(F1Application.getUserId());
                    F1Application.setLedgerUpdateTime();
                    Log.i(TAG, "数据库下载完成");
                    FileUtil.unzipSingleFileHereWithFileName(AppConfig.DB_FILE_PATh + File.separator + "SCGLXT.db.zip", "SCGLXT.db");
                    tvUpdateTime.setText(F1Application.getDbUpdateDate(F1Application.getUserId()));
                    ModifyDb.getInstance(getApplicationContext()).setAllTaskStatus("未完成");
                    new UpdateTaskStatus().execute();

                    if (isShowNotify)
                        manager.cancelAll();
                    isDowning = false;
                    isShowNotify = false;
                    dismissDialog(0);
                    MessageUtil.showToast(getApplicationContext(), "下载数据库成功");

                } catch (Exception e) {
                    //   handler.sendEmptyMessage(1);
                    dismissDialog(0);
                    Log.i(TAG, "下载出错");
                }
            } else {
                MessageUtil.showToast(getApplicationContext(), "下载失败");
            }
        }

        /* 处理UI线程，会被多次调用,触发事件为publicProgress方法 */
        @Override
        protected void onProgressUpdate(Integer... values) {
            /* 进度显示 */
            //      Log.i(TAG, values[0] + "");
            pdialog.setProgress(values[0]);
//            notif.contentView.setTextViewText(R.id.content_view_text1, values[0] + "%");
//            notif.contentView.setProgressBar(R.id.content_view_progress, 100, values[0], false);
//            manager.notify(0, notif);
        }
    }

    class UpdateTaskStatus extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            List<TaskModel> taskModelList = QueryDb.getInstance(getApplication()).getAllTask();
            StringBuffer list = new StringBuffer();
            list.append("{\"list\":[");
            for (int i = 0; i < taskModelList.size(); i++) {
                list.append("{\"task_id\":");
                list.append("\"");
                list.append(taskModelList.get(i).guid);
                list.append("\"");
                list.append(",");
                list.append("\"task_status\":\"已下载\"}");
                if (i < taskModelList.size() - 1) {
                    list.append(",");
                }
            }
            list.append("]}");
            Log.i(TAG, "上传任务状态参数：" + list);
            String url = AppConfig.BASE_URL + Constants.UPLOAD_TASK_STATUS_URL;
            Log.i(TAG, "上传任务状态url:" + url);
            Map<String, String> map = new HashMap<>();
            map.put("list", list.toString());
            String result = new HttpClient(getApplicationContext()).doPost(url, map);
            Log.i(TAG, "上传任务状态返回结果:" + result);
            return null;
        }
    }


    class GetFileSizeTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            String url = AppConfig.BASE_URL + params[0];
            Log.i(TAG, url);
            String result = new HttpClient(getApplicationContext()).doGet(url);
            Log.i(TAG, "请求文件大小返回结果：" + result);
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            try {
                JSONObject json = new JSONObject(s);
                fileSize = json.getLong("file_size");
                dbSize = json.getLong("dbsize");
                if (fileSize == 0) {
                    fileSize = 60 * 1024 * 1024;
                }
                file_num = json.getInt("count");

                MessageUtil.showProgressDialog(ConfigActivity.this, "正在初始化数据库");
                new InitDbTask().execute(Constants.INIT_DB_URL);

            } catch (JSONException e) {
                MessageUtil.showProgressDialog(ConfigActivity.this, "正在初始化数据库");
                new InitDbTask().execute(Constants.INIT_DB_URL);
                e.printStackTrace();
            }
        }
    }

    class InitDbTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            String result = "";
            String url = AppConfig.BASE_URL + params[0];
            Log.i(TAG, "初始化数据库url：" + url);
            result = new HttpClient(getApplicationContext()).doGet(url);
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Log.i(TAG, "初始化数据库返回结果：" + s);
            MessageUtil.dismissProgressDialog();
            try {
                JSONObject json = new JSONObject(s);
                if (json.getString("successful").equals("true")) {
                    Log.i(TAG, "DB初始化成功");
                    showFirstDownPop();
                } else {
                    MessageUtil.showToast(getApplication(), "初始化失败");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private class LoginTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            String url = AppConfig.BASE_URL + Constants.LOGIN_URL;
            Log.i(TAG, "登陆url：" + url);
            String result = "";
            Map<String, String> map = new HashMap<>();
            map.put("username", params[0]);
            map.put("password", params[1]);
            map.put("pageStyle", "");
            map.put("logined", params[0]);
            map.put("agent", "1");
            result = new HttpClient(getApplicationContext()).doPost(url, map);
            Log.i(TAG, "登陆返回结果：" + result);
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Gson gson = new Gson();
            try {
                User4Json uj = gson.fromJson(s, new TypeToken<User4Json>() {
                }.getType());
                if (uj.successful.equals("true")) {
                    MessageUtil.showToast(getApplicationContext(), "验证成功");
                    F1Application.setUserName(uj.resultValue.persName);
                    F1Application.setUserId(uj.resultValue.persGuid);
                    new GetFileSizeTask().execute(Constants.GET_FILE_SIZE_URL);
                } else {
                    MessageUtil.showToast(getApplicationContext(), uj.resultHint);
                    HttpCookies.setSessionId(null);
                }
            } catch (Exception e) {
                MessageUtil.showToast(getApplicationContext(), "验证失败");
            }
        }
    }

    private void registerHomeKeyReceiver(Context context) {
        reciver = new HomeWatchereciver();
        final IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        context.registerReceiver(reciver, homeFilter);
    }

    private void unregisterHomeKeyReceiver(Context context) {
        if (null != reciver) {
            context.unregisterReceiver(reciver);
        }
    }

    public class HomeWatchereciver extends BroadcastReceiver {
        private static final String SYSTEM_DIALOG_REASON_KEY = "reason";
        private static final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
        private static final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
        private static final String SYSTEM_DIALOG_REASON_LOCK = "lock";
        private static final String SYSTEM_DIALOG_REASON_ASSIST = "assist";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.i(TAG, "onReceive: action: " + action);
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                // android.intent.action.CLOSE_SYSTEM_DIALOGS
                String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
                Log.i(TAG, "reason: " + reason);

                if (SYSTEM_DIALOG_REASON_HOME_KEY.equals(reason)) {
                    // 短按Home键
                    Log.i(TAG, "homekey");

                    if (isDowning) {
                        Log.i(TAG, "Show Notify");
                        isShowNotify = true;
                        Intent intent1 = new Intent(ConfigActivity.this, ConfigActivity.class);
                        PendingIntent pIntent = PendingIntent.getActivity(ConfigActivity.this, 0, intent1, 0);
                        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                        notif = new Notification();
                        notif.icon = R.drawable.logo;
                        notif.tickerText = "";
                        //View notifyView = LayoutInflater.from(ConfigActivity.this).inflate(R.layout.notify_down_db,null);
                        notif.contentView = new RemoteViews(getPackageName(), R.layout.notify_down_db);
                        notif.contentIntent = pIntent;
                        int str1 = (int) (currentFileSize * 100 / size);
                        notif.contentView.setTextViewText(R.id.content_view_text1, str1 + "%");
                        notif.contentView.setProgressBar(R.id.content_view_progress, 100, str1, false);
                        manager.notify(0, notif);
                    }
                } else if (SYSTEM_DIALOG_REASON_RECENT_APPS.equals(reason)) {
                    // 长按Home键 或者 activity切换键
                    Log.i(TAG, "long press home key or activity switch");

                } else if (SYSTEM_DIALOG_REASON_LOCK.equals(reason)) {
                    // 锁屏
                    Log.i(TAG, "lock");
                } else if (SYSTEM_DIALOG_REASON_ASSIST.equals(reason)) {
                    // samsung 长按Home键
                    Log.i(TAG, "assist");
                }
            }
        }
    }


}